from flask import Blueprint, jsonify, request, json
from R_CMgmt.riskCopeOperation import emergencyOprt

emergency = Blueprint('emergency', __name__)


@emergency.route('/init', methods=['GET'])
def init():
    json_str = emergencyOprt.getAllEmergency()
    if json_str == 0:
        return json_str

    return jsonify(json_str)


@emergency.route('/getEmergencyWithCopeID', methods=['POST'])
def getEmergencyWithCopeID():
    data = request.get_data()
    json_data = json.loads(data.decode("utf-8"))
    risk_cope_id = json_data.get('risk_cope_id')

    json_str = emergencyOprt.getEmergencyWithCopeIDFromDB(risk_cope_id)
    if json_str == 0:
        return json_str

    return jsonify(json_str)


@emergency.route('/editEmergency', methods=['POST'])
def editEmergency():
    data = request.get_data()
    json_data = json.loads(data.decode("utf-8"))
    risk_cope_id = json_data.get('risk_cope_id')
    content = json_data.get('content')

    if emergencyOprt.getEmergencyWithCopeIDFromDB(risk_cope_id):
        emergencyOprt.editEmergencyFromDB(risk_cope_id)
        return jsonify(1)
    else:
        emergencyOprt.addEmergencyToDB(risk_cope_id, content)
        return jsonify(2)